package com.hound.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UploadAndDownController {

    @RequestMapping(value = "/toUpload")
    public String toUpload(){
        return "upload";
    }

    @ResponseBody
    @RequestMapping(value = "upload")
    public Map<String, String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, String> res = new HashMap<>();
        if (!file.isEmpty()) {
            String upPath = "D:\\upload";
            String filename = file.getOriginalFilename();
            File f = new File(upPath, filename);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            file.transferTo(f);
            res.put("status", "200");
        } else {
            res.put("status", "0");
        }
        return res;
    }


    @RequestMapping(value = "downLoad")
    public ResponseEntity<byte[]> downLoad() throws Exception {
        String fileName = "小米之家--申请单.csv";
        File file = new File("D:\\upload", fileName);
        HttpHeaders httpHeaders = new HttpHeaders();
        String downFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");//少了这句，可能导致下载中文文件名的文档，只有后缀名的情况
        httpHeaders.setContentDispositionFormData("attachment", downFileName);//告知浏览器以下载方式打开
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);//设置MIME类型
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.CREATED);
    }


}
